<template>
    <div class="goods-add-form">
        <div class="section">
            <h2 class="section-title">基础信息</h2>
            <el-form ref="ruleFormRef" style="max-width: 1200px;margin: 20px;" :model="purchase_return" status-icon
                :rules="rules" label-width="auto" class="demo-ruleForm">
                <div style="display: flex; justify-content: space-between;">
                    <div style="width: 48%;">
                        <el-form-item label="采购退货单号" style="margin-bottom: 30px;">
                            <el-input v-model="purchase_return.purret_code" placeholder="自动获取编号" readonly/>
                        </el-form-item>
                        <el-form-item label="采购订单编号" style="margin-bottom: 30px;">
                            <el-input v-model="purchase_return.po_code" placeholder="采购订单编号" disabled />
                        </el-form-item>
                        <el-form-item label="供应商名称" style="margin-bottom: 30px;">
                            <el-input v-model="purchase_return.vendor_name" placeholder="供应商名称" disabled />
                        </el-form-item>
                        <el-form-item prop="warehouse_code" label="退货仓库" style="margin-bottom: 30px;">
                            <el-select v-model="purchase_return.warehouse_code" placeholder="请选择退货仓库"
                                @change="handleSelectChange">
                                <el-option v-for="item in Weahouse" :key="item.warehouse_code"
                                    :label="item.warehouse_name" :value="item.warehouse_code" />
                            </el-select>
                        </el-form-item>
                    </div>

                    <div style="width: 48%;">
                    <el-form-item label="采购订单" prop="po_name" style="margin-bottom: 30px;">
                            <el-input v-model="purchase_return.po_name" placeholder="请点击查询采购订单" clearable
                                readonly class="order-input" @click="showOrderDialog">
                                <template #append>
                                    <el-button icon="Search" @click="showOrderDialog" />
                                </template>
                            </el-input>
                        </el-form-item>
                        <el-form-item label="退货日期" style="margin-bottom: 30px;" prop="purret_returntime">
                            <el-date-picker v-model="purchase_return.purret_returntime" type="date"
                                placeholder="请选择退货日期" :size="size" style="width: 460px;"
                                value-format="YYYY-MM-DDTHH:mm:ss.SSSZ" :editable="false" />
                        </el-form-item>
                        <el-form-item label="退货原因" prop="purret_returncause" style="margin-bottom: 30px;">
                            <el-input v-model="purchase_return.purret_returncause" type="textarea" 
                                placeholder="请输入退货原因" />
                        </el-form-item>
                    </div>
                </div>
            </el-form>
        </div>

        <div class="section">
            <h2 class="section-title">退货产品明细</h2>
            <div style="float: left;margin: 10px 0px;">
                <el-button type="primary" @click="detailstAdd">添加</el-button>
                <el-button @click="productDel">移除</el-button>
            </div>
            <el-table :data="selectedDetailsData" border style="width: 100%" :cell-style="{ textAlign: 'center' }"
                :header-cell-style="{
                    textAlign: 'center',
                    background: '#f5f7fa',
                    fontWeight: 'bold',
                    position: 'sticky',
                    top: 0
                }" ref="selectedTable" @selection-change="handleSelectedChange">
                <el-table-column type="selection" width="55" />
                <el-table-column prop="pro_name" label="产品名称" />
                <el-table-column prop="pro_code" label="产品编号" width="160" />
                <el-table-column prop="pro_brand" label="品牌" width="100" />
                <el-table-column prop="pro_model" label="规格型号" />
                <el-table-column prop="unitmeas_id" label="单位" width="70">
                    <template #default="scope">
                        <span>{{ measureValue(scope.row.unitmeas_id) }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="po_number" label="采购数量" />
                <el-table-column prop="details_storage" label="已入库数量" />
                <!-- <el-table-column prop="podet_notstocked" label="待入库数量" /> -->
                <el-table-column prop="number_returns" label="本次退货数量">
                    <template #default="scope">
                        <el-input v-model="scope.row.number_returns" style="width: 75px" :precision="2" :min="0" 
                            :max="scope.row.podet_inbound_quantity" />
                    </template>
                </el-table-column>
            </el-table>
            <div style="height: 40px; line-height: 40px;">
                <div style="display: inline-block; float: left;">合计</div>
                <div style="display: inline-block; float: right;">
                    采购总数量：{{ purchase_total_qty }} &nbsp;&nbsp;&nbsp;
                    已入库总数：{{ inbound_total_qty }} &nbsp;&nbsp;&nbsp;
                    本次退货总数：{{ return_total_qty }}
                </div>
            </div>
        </div>

        <div class="button-group" style="position: absolute; bottom: 10px; right: 64px; display: flex; gap: 10px;">
            <el-button type="primary" @click="handleAdd">保存</el-button>
            <el-button @click="handleClose">关闭</el-button>
        </div>
    </div>

    <el-dialog v-model="proSaleTableVisible" width="930" title="添加采购订单">
        <hr>
        <div style="margin: 10px 0px;">
            <div style="float: left;margin: 10px 0px;">
                <el-input size="small" v-model="orderCode" style="width: 240px;margin-right: 20px;" placeholder="请输入采购单号" />
                <el-select size="small" v-model="orderStatus" placeholder="请选择单据状态" @change="customerEndit"
                    style="width: 240px;margin-right: 20px;">
                    <el-option v-for="item in statusOpt" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
                <el-select size="small" v-model="customerName" placeholder="请选择供应商" @change="customerEndit" style="width: 240px;">
                    <template #header>
                        <el-input v-model="customer_name" placeholder="搜索供应商" style="padding: 5px"
                            @input="getCustomerDebounced" />
                    </template>
                    <el-option v-for="item in customerOptons" :key="item.vendor_code" :label="item.vendor_name"
                        :value="item.vendor_code" />
                </el-select>
            </div>
            <div style="float: left;margin: 10px 0px;">
                <el-select size="small" v-model="repId" placeholder="请选择采购员" style="width: 240px;margin-right: 20px;">
                    <template #header>
                        <el-input v-model="user_name" placeholder="搜索采购员" style="padding: 5px;"
                            @input="userFillDebounced" />
                    </template>
                    <el-option v-for="item in userOpt" :key="item.user_id" :label="item.user_name"
                        :value="item.user_id" />
                </el-select>
                <el-tree-select size="small" v-model="deptId" :data="deptOpt" :props="defaultProps" style="width: 240px;"
                    :check-strictly="true" placeholder="请选择采购部门" @change="getUser()">
                    <template #header>
                        <el-input size="small" v-model="dept_name" placeholder="搜索采购部门" style="padding: 5px"
                            @input="deptFillDebounced" />
                    </template>
                </el-tree-select>
            </div>
            <div style="float: right;margin: 10px 0px;">
                <el-button @click="orderReaslt">重置</el-button>
                <el-button type="primary" @click="orderEedit">
                    查询
                </el-button>
            </div>
        </div>
        <el-table ref="multipleTableRef" :data="orderData" :cell-style="{ textAlign: 'center' }" :header-cell-style="{
            textAlign: 'center',
            background: '#f5f7fa',
            fontWeight: 'bold',
            position: 'sticky',
            top: 0
        }">
            <el-table-column width="55">
                <template #default="scope">
                    <el-radio class="radio" :label="scope.row" v-model="currentRow">&emsp;&emsp;&emsp;</el-radio>
                </template>
            </el-table-column>
            <el-table-column property="po_Code" label="采购编号" width="160" />
            <el-table-column property="po_Name" label="采购名称" width="160" />
            <el-table-column property="po_State" label="单据状态" width="80">
                <template #default="scope">
                    <span>{{ scope.row.po_State == 0 ? '待入库' : '部分入库' }}</span>
                </template>
            </el-table-column>
            <el-table-column property="po_Vendor_Name" label="供应商" />
            <!-- <el-table-column property="po_depd_id" label="采购部门">
                <template #default="scope">
                    <span>{{ deptValue(scope.row.po_depd_id) }}</span>
                </template>
            </el-table-column> -->
            <el-table-column property="po_Rep_Id" label="采购负责人">
                <template #default="scope">
                    <span>{{ userValue(scope.row.po_Rep_Id) }}</span>
                </template>
            </el-table-column>
            <el-table-column property="po_quantity_purchased" label="采购数量" />
            <el-table-column property="po_amount" label="采购金额" />
        </el-table>
        <br>
        <div style="text-align: center;display: flex; justify-content: center;">
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 20, 50]"
                :small="false" :background="true" layout="total, sizes, prev, pager, next, jumper" :total="pageCount"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" size="small" />
        </div>
        <hr>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="handleConfirmColse">取消</el-button>
                <el-button type="primary" @click="handleConfirmSelection">
                    确定
                </el-button>
            </div>
        </template>
    </el-dialog>

    <el-dialog v-model="proDetailsTableVisible" width="850" title="添加采购明细">
        <hr>
        <div style="margin: 10px 0px;">
            <div style="float: left;margin: 10px 0px;">
                <el-input v-model="productName" style="width: 240px;margin-right: 20px;" placeholder="请输入产品编号/名称" />
                <el-select v-model="dict_code" placeholder="请选择单位" style="width: 240px">
                    <el-option v-for="item in measureOptios" :key="item.dict_value" :label="item.dict_label"
                        :value="item.dict_value" />
                </el-select>
            </div>
            <div style="float: right;margin: 10px 0px;">
                <el-button @click="detalisReaslt">重置</el-button>
                <el-button type="primary" @click="detailsEedit">
                    查询
                </el-button>
            </div>
        </div>
        <el-table ref="multipleTableDetailsRef" :data="detailsData" :cell-style="{ textAlign: 'center' }"
            :header-cell-style="{
                textAlign: 'center',
                background: '#f5f7fa',
                fontWeight: 'bold',
                position: 'sticky',
                top: 0
            }" @selection-change="handleSelectedChange" >
            <el-table-column type="selection" width="55" :selectable="isDisabled" />
            <el-table-column prop="pro_name" label="产品名称" />
            <el-table-column prop="pro_code" label="产品编号" width="160" />
            <el-table-column prop="pro_brand" label="品牌" width="100" />
            <el-table-column prop="pro_model" label="规格型号" />
            <el-table-column prop="unitmeas_id" label="单位" width="70">
                <template #default="scope">
                    <span>{{ measureValue(scope.row.unitmeas_id) }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="po_number" label="采购数量" />
            <el-table-column prop="details_storage" label="已入库数量" />
            <!-- <el-table-column prop="podet_notstocked" label="待入库数量" /> -->
            <el-table-column prop="sun" label="待入库数量">
                <template #default="scope">
                    <span>{{ drkValue(scope.row) }}</span>
                </template>
                </el-table-column>
        </el-table>
        <br>
        <div style="text-align: center;display: flex; justify-content: center;">
            <el-pagination v-model:current-page="detailsCurrentPage" v-model:page-size="detailsPageSize"
                :page-sizes="[5, 10, 20, 50]" :small="false" :background="true"
                layout="total, sizes, prev, pager, next, jumper" :total="detailsPageCount"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" size="small" />
        </div>
        <hr>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="handleConfirmDetailsClose">取消</el-button>
                <el-button type="primary" @click="handleConfirmDetailsSelection">
                    确定
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script>
import { ref, reactive, onMounted, inject, watch, toRaw } from 'vue'
import dayjs from 'dayjs'
import axios from 'axios'
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { debounce } from 'lodash';
export default {
    setup() {
        const purchase_return = reactive({
            purret_code: "", // 退货单号
            po_id: "", // 采购订单ID
            po_name: "", // 采购订单名称
            po_code: "", // 采购订单编号
            vendor_name: "", // 供应商名称
            vendor_code: "", // 供应商编号
            purret_returntime: "", // 退货日期
            purret_returncause: "", // 退货原因
            pu_state: "", // 退货状态
            remark: "", // 备注
            create_by: "", // 创建人
            create_time: "", // 创建时间
            del_flag: 0, // 删除标志
            warehouse_code: "" // 仓库编码
        })

        const ruleFormRef = ref(null)
        const rules = reactive({
            purret_returntime: [
                { required: true, message: "退货日期不能为空", trigger: ['blur', 'change'] },
            ], 
            warehouse_code: [
                { required: true, message: "退货仓库不能为空", trigger: ['blur', 'change'] },
            ], 
            po_name: [
                { required: true, message: "采购订单不能为空", trigger: ['blur', 'change'] },
            ],
            purret_returncause: [
                { required: true, message: "退货原因不能为空", trigger: ['blur', 'change'] },
            ]
        });

        const Weahouse = ref([]);//仓库信息
        const userOptions = ref([])//用户信息
        const deptOptions = ref([])//部门信息
        const proSaleTableVisible = ref(false)
        const proDetailsTableVisible = ref(false)
        const deptName = ref("")
        const userName = ref("")
        const orderData = ref([])
        const currentPage = ref(1)
        const pageSize = ref(5)
        const pageCount = ref(0)
        const detailsCurrentPage = ref(1)
        const detailsPageSize = ref(5)
        const detailsPageCount = ref(0)
        const productName = ref("")
        const dict_code = ref("")
        const userOpt = ref([])
        const currentRow = ref(null)
        const proData = ref()
        const orderCode = ref("")//记录用户输入的采购单号
        const orderStatus = ref("")//记录用户选择的单据状态
        const customerName = ref("")//记录用户选择的供应商
        const repId = ref("")//记录用户选择的采购负责人
        const deptId = ref("")//记录用户选择的采购部门
        const customerOptons = ref([])
        const customer_name = ref("")
        const user_name = ref("")
        const deptOpt = ref([])
        const dept_name = ref("")
        const detailsData = ref([])
        const measureOptios = ref([])
        const selectedTable = ref(null)//表格引用
        const multipleTableDetailsRef = ref(null)//明细表格引用
        const selectedDetailesRows = ref([]);//存储选中的数据
        const selectedDetailsData = ref([]); // 最终确认选择的数据
        const purchase_total_qty = ref(0)//记录采购总数量
        const inbound_total_qty = ref(0)//记录已入库数量
        const return_total_qty = ref(0)//记录本次退货数量
        const router = useRouter()
        const statusOpt = ref([{
            label: "待入库",
            value: "0"
        }, {
            label: "部分入库",
            value: "2"
        }, {
            label: "全部入库",
            value: "3"
        }
    ])

        onMounted(() => {
            getMeasure()
            userFill()
            deptFill()
            getCustomer()
            WeahousesSelect()
            getDept()
            orderFill()
            orderCount()
        })

        watch(selectedDetailsData, (newVal) => {
            //每次计算时清空累加
            purchase_total_qty.value = 0
            inbound_total_qty.value = 0
            return_total_qty.value = 0
            
            newVal.forEach(row => {
                if (isNaN(Number(row.number_returns))) {
                    ElMessage.warning('退货数量必须是数字');
                    row.number_returns = 0;
                }
                
                // 退货数量不能大于已入库数量
                // if (row.number_returns > row.details_storage) {
                //     ElMessage.warning('退货数量不能大于入库数量');
                //     row.number_returns = row.details_storage;
                // } 
                // 再检查累计退货数量是否超过入库数量
                // else if (Number(row.number_returns) + Number(row.podet_retqty) > row.details_storage) {
                //     ElMessage.warning('本次入库数量已全部退货');
                //     row.number_returns = 0;
                // }
                if(row.number_returns>row.po_number){
                    ElMessage.warning('退货数量不能大于采购数量');
                    row.number_returns = row.po_number
                    
                }

                purchase_total_qty.value += Number(row.po_number)
                inbound_total_qty.value += Number(row.details_storage)
                return_total_qty.value += Number(row.number_returns)
            });
        }, { deep: true });

        // 查询仓库信息
        function WeahousesSelect() {
            axios.get("http://localhost:5181/api/Db_warehouse/WarehouseBySelect", {
                headers: {
                    'Authorization': 'Bearer ' + localStorage.getItem('token')
                }
            }).then((res) => {
                Weahouse.value = res.data;
            }).catch((res) => {
                console.log(res)
            })
        }

        // 选择退货仓库事件触发
        const handleSelectChange = (selectedValue) => {
            const selectedItem = Weahouse.value.find(item => item.warehouse_code === selectedValue);
            purchase_return.warehouse_name = selectedItem.warehouse_name;
        };

        //防抖函数0.5秒后进行查询
        const getDeptDebounced = debounce(getDept, 500);
        function getDept() {
            axios.get("http://localhost:5181/api/Dept/Get_Dept_Trees", {
                params: {
                    name: deptName.value
                },
                headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                deptOptions.value = convertToTreeOptions(result.data)
            }).catch((err) => {
                console.info(err)
            });
        }

        function deptValue(row) {
            if (!row) return "无";
            // 直接从已加载的deptOptions中查找
            const found = findDeptById(deptOptions.value, row);
            return found ? found.label : "无";
        }

        // 递归查找部门
        function findDeptById(nodes, id) {
            for (const node of nodes) {
                if (node.value === id) return node;
                if (node.children) {
                    const found = findDeptById(node.children, id);
                    if (found) return found;
                }
            }
            return null;
        }

        const userFillDebounced = debounce(userFill, 500)
        function userFill() {
            axios.get("http://localhost:5181/api/User/GetUsers", {
                params: {
                    dept: 0,
                    name: user_name.value
                },
                headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                userOpt.value = result.data
            }).catch((err) => {
                console.info(err)
            });
        }

        const deptFillDebounced = debounce(deptFill, 500);
        function deptFill() {
            axios.get("http://localhost:5181/api/Dept/Get_Dept_Trees", {
                params: {
                    name: dept_name.value
                },
                headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                deptOpt.value = convertToTreeOptions(result.data)
            }).catch((err) => {
                console.info(err)
            });
        }

        function userValue(row) {
            if (!row) return "无";
            const parentUser = userOpt.value.find((user) => user.user_id == row)
            return parentUser ? parentUser.user_name : "无"
        }

        const getUserDebounced = debounce(getUser, 500);
        function getUser() {
            axios.get("http://localhost:5181/api/User/GetUsers", {
                params: {
                    dept: purchase_return.po_dept_id,
                    name: userName.value
                },
                headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                userOptions.value = result.data
            }).catch((err) => {
                console.info(err)
            });
        }

        //把二维数据转换为结构数据
        const convertToTreeOptions = (items) => {
            return items.map(item => ({
                value: item.dept_id,
                label: item.dept_name,
                children: item.children && item.children.length > 0
                    ? convertToTreeOptions(item.children)
                    : []
            }))
        }

        //查询计量单位
        function getMeasure() {
            axios.get("http://localhost:5181/api/Dict/Get_Dict_Datas", {
                params: {
                    dict_type: "db_measure"
                }, headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                measureOptios.value = result.data
                measureOptios.value = [{
                    dict_value: "0", dict_label: "请选择单位"
                }, ...result.data]
            }).catch((err) => {
                console.info(err)
            });
        }

        //根据计量单位id返回计量单位名称
        function measureValue(row) {
            if (!row) return "无";
            const parentDept = measureOptios.value.find((sex) => sex.dict_value == row);
            return parentDept ? parentDept.dict_label : "无";
        }

        function drkValue(row){
            const sun = Number(row.po_number)-Number(row.details_storage)
            // console.log(sun);
            return sun
        }
        function showOrderDialog() {
            proSaleTableVisible.value = true
        }

        //查询采购订单信息
        function orderFill() {
            axios.get("http://localhost:5181/api/Po/GetPoWhere2", {
                params: {
                    currentPage: currentPage.value,
                    pageSize: pageSize.value,
                    Po_Code: orderCode.value,
                    Po_State: orderStatus.value == "" ? -1 : Number(orderStatus.value),
                    Po_Vendor_Name: customerName.value,
                    Po_Rep_Id: repId.value == "" ? 0 : Number(repId.value),
                    Po_depd_id: deptId.value == "" ? 0 : Number(deptId.value)
                },
                headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                orderData.value = result.data
                // console.log(orderData)
            }).catch((err) => {
                console.info(err)
            });
        }

        //查询采购订单总数
        function orderCount() {
            axios.get("http://localhost:5181/api/Po/GetPoWhereCount2", {
                params: {
                    Po_Code: orderCode.value,
                    Po_State: orderStatus.value == "" ? -1 : Number(orderStatus.value),
                    Po_Vendor_Name: customerName.value,
                    Po_Rep_Id: repId.value == "" ? 0 : Number(repId.value),
                    Po_depd_id: deptId.value == "" ? 0 : Number(deptId.value)
                },
                headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                pageCount.value = result.data
            }).catch((err) => {
                console.info(err)
            });
        }

        const getCustomerDebounced = debounce(getCustomer, 500)
        //查询供应商信息
        function getCustomer() {
            axios.get("http://localhost:5181/api/Values/Pinv_VendorWhere", {
                params: {
                    Vendor_name: customer_name.value
                }, headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                customerOptons.value = result.data
            }).catch((err) => {
                console.info(err)
            });
        }

        function handleSizeChange(val) {
            pageSize.value = val;
            orderFill();
        }

        function handleCurrentChange(val) {
            currentPage.value = val;
            orderFill();
        }

        //点击确定获取采购订单信息
        function handleConfirmSelection() {
            if (currentRow.value) {
                proData.value = currentRow.value
                purchase_return.po_name = proData.value.po_Name
                purchase_return.po_code = proData.value.po_Code
                purchase_return.vendor_name = proData.value.po_Vendor_Name
                purchase_return.vendor_code = proData.value.po_Endor_Code
                purchase_return.po_id = proData.value.po_Id
                purchase_return.remark = proData.value.remark
                proSaleTableVisible.value = false
                fillPurchaseDetails()
                fillPurchaseDetailsCount()
                currentRow.value = null
            } else {
                ElMessage.warning('请选择要退货的采购订单数据');
                return;
            }
        }

        //条件查询按钮
        function orderEedit() {
            orderFill()
            orderCount()
        }

        //重置按钮
        function orderReaslt() {
            orderCode.value = ""
            orderStatus.value = ""
            customerName.value = ""
            repId.value = ""
            deptId.value = ""
            orderFill()
            orderCount()
        }

        //取消按钮
        function handleConfirmColse() {
            orderCode.value = ""
            orderStatus.value = ""
            customerName.value = ""
            repId.value = ""
            deptId.value = ""
            proSaleTableVisible.value = false
        }

        //添加采购明细按钮
        function detailstAdd() {
            proDetailsTableVisible.value = true
        }

        //取消采购明细按钮
        function handleConfirmDetailsClose() {
            productName.value = ""
            dict_code.value = ""
            proDetailsTableVisible.value = false
        }

        //根据采购订单编号获取对应采购订单明细
        async function fillPurchaseDetails() {
            try {
                const result = await axios.get("http://localhost:5181/api/Po/GetdetailswherecodeFY", {
                    params: {
                        currentPage: detailsCurrentPage.value,
                        pageSize: detailsPageSize.value,
                        code: purchase_return.po_code,
                        procode: productName.value,
                        unitmeas_id: dict_code.value == "" ? 0 : dict_code.value
                    },
                    headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
                });

                detailsData.value = result.data.map((item) => ({
                    ...item,
                    number_returns: 0
                }));

                // console.info("处理后的数据:", detailsData.value);
            } catch (err) {
                console.error("请求失败:", err);
            }
        }

        //查询采购订单明细总数
        function fillPurchaseDetailsCount() {
            axios.get("http://localhost:5181/api/Po/GetdetailswherecodeFYCount", {
                params: {
                    code: purchase_return.po_code,
                    procode: productName.value,
                    unitmeas_id: dict_code.value == "" ? 0 : dict_code.value
                }, headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
            }).then((result) => {
                detailsPageCount.value = result.data
            }).catch((err) => {
                console.info(err)
            });
        }

        function detailsEedit() {
            fillPurchaseDetails()
            fillPurchaseDetailsCount()
        }

        function detalisReaslt() {
            productName.value = ""
            dict_code.value = ""
            fillPurchaseDetails()
            fillPurchaseDetailsCount()
        }

        //表格选择变化时处理数据
        const handleSelectedChange = (val) => {
            selectedDetailesRows.value = val;
        };

        //点击确定保存选中的采购明细数据
        const handleConfirmDetailsSelection = () => {
            const newItems = selectedDetailesRows.value.map(item => ({
                ...item
            }));

            // 合并数据（去重）
            selectedDetailsData.value = [
                ...selectedDetailsData.value,
                ...newItems.filter(newItem =>
                    !selectedDetailsData.value.some(existItem =>
                        existItem.pro_code === newItem.pro_code
                    )
                )
            ];
            multipleTableDetailsRef.value?.clearSelection();
            handleConfirmDetailsClose();
        }

        //判断已添加过的产品数据不能再次添加
        const isDisabled = (row) => {
            return !selectedDetailsData.value.some(item => item.pro_code === row.pro_code);
        };

        //移除选中的table控件数据
        const productDel = () => {
            if (selectedDetailesRows.value.length === 0) {
                ElMessage.warning('请先选择要移除的数据');
                return;
            }

            // 根据pro_code过滤要保留的数据
            const selectedCodes = selectedDetailesRows.value.map(item => item.pro_code);
            selectedDetailsData.value = selectedDetailsData.value.filter(
                item => !selectedCodes.includes(item.pro_code)
            );

            selectedTable.value?.clearSelection();
            selectedDetailesRows.value = [];
        };

        //添加采购退货信息
        function handleAdd() {
            ruleFormRef.value.validate(async (valid, fields) => {
                if (valid) {
                    if (selectedDetailsData.value.length > 0) {
                        obtainCode().then(() => {
                            returnAdd()
                        }).catch((err) => {
                            console.info(err)
                        });
                        // returnAdd()
                    } else {
                        ElMessage.warning('请选择要添加的产品数据');
                        return;
                    }
                }
            })
        }

        function obtainCode() {
            return axios.get("http://localhost:5181/api/DJBH/DJBH", {
                params: {
                    en_code: 18 // 采购退货单编号类型
                }
            }).then((result) => {
                purchase_return.purret_code = result.data
            }).catch((err) => {
                console.info(err)
            });
        }
        
        function returnAdd() {
            // 构建主表数据
            const pinvPuOrderDto = {
                po_id: purchase_return.po_id,
                purret_code: purchase_return.purret_code,
                vendor_name: purchase_return.vendor_name,
                vendor_code: purchase_return.vendor_code,
                po_code: purchase_return.po_code,
                po_name: purchase_return.po_name,
                purret_returntime: purchase_return.purret_returntime,
                purret_returncause: purchase_return.purret_returncause,
                pu_state: "0", // 初始状态为0
                Pu_audit:"0",//审核状态
                remark: purchase_return.remark,
                create_by: localStorage.getItem('userLName'),
                create_time: dayjs().format('YYYY-MM-DDTHH:mm:ss.SSSZ'),
                del_flag: "0",
                warehouse_code: purchase_return.warehouse_code
            };

            // 构建明细数据列表
            const puDetailsAddDtos = selectedDetailsData.value.map(item => ({
                purret_id: 0,//采购退货id
                po_code: purchase_return.po_code,
                pro_name: item.pro_name,
                pro_code: item.pro_code,
                pro_brand: item.pro_brand,
                pro_model: item.pro_model,
                unitmeas_id: item.unitmeas_id,
                po_number: item.po_number,
                podet_inbound_quantity: item.details_storage,
                podet_notstocked: Number(item.po_number)-Number(item.details_storage),
                Number_returns: item.podet_retqty,
                Podet_retqty: item.number_returns
            }));

            // 组装最终请求对象
            const requestData = {
                pinv_Pu_Order_Dto: pinvPuOrderDto,
                pu_Details_Add_Dtos: puDetailsAddDtos
            };
            // console.log(requestData)
            // console.log(selectedDetailsData)
            axios.post("http://localhost:5181/api/Pu/PostPuAdd", requestData, {
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${localStorage.getItem('token')}`
                    }
                }).then((result) => {
                    if (result.data > 0) {
                        ElMessage({
                            type: 'success',
                            message: '采购退货单添加成功！'
                        });
                        handleClose()
                    }
                }).catch((err) => {
                    console.info(err)
                });
        }

        const closeTab = inject('closeTab'); // 注入关闭方法
        function handleClose() {
            const targetPath = "/main/Pinv/Pu";

            if (closeTab) {
                closeTab(); // 调用父组件提供的关闭方法
            }

            // 添加目标标签页（如果不存在）
            const tabs = inject('editableTabs');
            if (tabs && !tabs.value.some(tab => tab.path === targetPath)) {
                tabs.value.push({
                    title: "采购退货",
                    name: targetPath,
                    path: targetPath
                });
            }

            // 跳转并激活目标标签页
            const activeTab = inject('editableTabsValue');
            if (activeTab) {
                activeTab.value = targetPath;
            }

            router.push(targetPath);
        }

        return {
            purchase_return, Weahouse, handleSelectChange, userOptions, deptOptions, showOrderDialog, proSaleTableVisible,
            deptName, userName, getUserDebounced, getDeptDebounced, getUser, orderData, currentPage, pageSize, pageCount, handleSizeChange,
            handleCurrentChange, deptValue, userValue, userOpt, currentRow, handleConfirmSelection, orderCode, orderStatus, customerName, repId
            , deptId, customerOptons, customer_name, getCustomerDebounced, user_name, userFillDebounced, deptFillDebounced, dept_name, deptOpt,
            statusOpt, orderEedit, orderReaslt, proData, detailsData, measureOptios, measureValue, selectedTable,
            handleSelectedChange, proDetailsTableVisible, detailsCurrentPage, detailsPageCount, detailsPageSize, productName, dict_code,
            detailstAdd, detailsEedit, detalisReaslt, handleConfirmColse, handleConfirmDetailsClose, multipleTableDetailsRef, selectedDetailesRows,
            selectedDetailsData, handleConfirmDetailsSelection, isDisabled, productDel, purchase_total_qty, inbound_total_qty, return_total_qty,
            rules, ruleFormRef, handleAdd, handleClose,drkValue
        }
    }
}
</script>

<style scoped>
.goods-add-form {
    padding: 20px;
    background-color: #fff;
    margin-top: -40px;
}

.section {
    margin-bottom: 30px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    padding: 20px;
    /* 添加阴影效果 */
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    margin-top: -20px;
}

.section-title {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 15px;
}

.button-group {
    float: right;
    display: flex;
    position: flex;
    text-align: right;
    margin-top: 20px;
    height: 7%;
    align-items: center;
    width: 80.1%;
    background-color: #ffffff;
    justify-content: flex-end;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    padding-right: 20px;
}
</style>